bits 32
; count of dwords in the memory bitmap
; __declspec(naked) DWORD __fastcall AquireAvailableBit(DWORD cdBitmap, LPDWORD lpdwBitmap)
; ecx = cdBitmap count of dwords to be checked in the bitmap, mustn't be zero
; edx = lpdwBitmap pointer to bitmap
global AquireAvailableBit
AquireAvailableBit:
AquireAvailableBit.Try:
    test ecx, 0xFFFF_FFFF
    jz AquireAvailableBit.NoAvailableBit ; ecx 为 0 直接失败
    test dword [edx + ecx * 4 - 4], 0xFFFF_FFFF ; 检测是否有可用的空闲位
    jnz AquireAvailableBit.HasAvailableBit ; 非零，说明有可用的空闲位
AquireAvailableBit.Loop:
    loop AquireAvailableBit.Try ; 尝试下个 DWORD
    ; mov dword [g_dwMemoryPoolBitmapSearchIndex], 0 ; 索引设置为 0，表示此时无内存可分配
AquireAvailableBit.NoAvailableBit:
    mov eax, -1 ; 循环结束，分配失败，返回 -1
    ret
AquireAvailableBit.HasAvailableBit:
    bsr eax, [edx + ecx * 4 - 4] ; 从低位向高位扫描找到第一个空闲 bit 序号
    btr [edx + ecx * 4 - 4], eax ; 清空该 bit
    dec ecx
    shl ecx, 5 ; ecx *= 32
    add eax, ecx ; 返回分配的位相对于位图基址的偏移
    ret